//
//  SettingViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/6.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "SettingViewController.h"
#import "SettingTableViewCell.h"
#import "ChangePWViewController.h"
#import "ChangePhoneViewController.h"
#import "ChangePhoneViewController.h"
#import "LoginViewController.h"
#import "SettingSafeCodeViewController.h"
#import "ChangeSafeCodeViewController.h"

@interface SettingViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSDictionary *personalInfoDic;

@end

@implementation SettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"设置"];
    [self.view addSubview:self.tableView];
    //    [self getPersonalInfo];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self getPersonalInfo];
}
#pragma mark - 获取个人信息
- (void)getPersonalInfo
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=memberinfo&companyid=%@&code=%@&timestamp=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp]] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        
        if ([responseObject[@"status"] intValue] == 1) {
            self.personalInfoDic = responseObject;
            
        } else {
            [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
#pragma mark - tableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SettingTableViewCell *cell = [[SettingTableViewCell alloc] init];
    NSArray *array = @[@"修改密码",@"安全密码",@"换绑手机",@"清除缓存",@"退出登录"];
    cell.leftLB.text = array[indexPath.row];
    
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(90);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        // 修改密码
        ChangePWViewController *changePWVC = [[ChangePWViewController alloc] init];
        [self.navigationController pushViewController:changePWVC animated:YES];
        
    } else if (indexPath.row == 1) {
        // 安全密码
        if ([self.personalInfoDic[@"buyPassSet"] intValue] == 0) {
            // 设置安全密码
            SettingSafeCodeViewController *settingSafeCodeVC = [[SettingSafeCodeViewController alloc] init];
            [self.navigationController pushViewController:settingSafeCodeVC animated:YES];
        } else if ([self.personalInfoDic[@"buyPassSet"] intValue] == 1) {
            // 修改安全密码
            ChangeSafeCodeViewController *changeSafeCodeVC = [[ChangeSafeCodeViewController alloc] init];
            [self.navigationController pushViewController:changeSafeCodeVC animated:YES];
        }
        
    } else if (indexPath.row == 2) {
        // 换绑手机
        ChangePhoneViewController *changePhoneVC = [[ChangePhoneViewController alloc] init];
        [self.navigationController pushViewController:changePhoneVC animated:YES];
        
    } else if (indexPath.row == 3) {
        // 清除缓存
        WeakSelf
        UIAlertController *alertController = [UIAlertController initWithMessage:@"是否清理缓存？" bolck:^(void) {
            [weakSelf clearFile];
        } cancelBolck:^(void) {
            
        }];
        [self presentViewController:alertController animated:YES completion:nil];
    } else if (indexPath.row == 4) {
        // 退出登录
        WeakSelf
        UIAlertController *alertController = [UIAlertController initWithMessage:@"是否退出登录？" bolck:^(void) {
            [MBProgressHUD showMessage:nil toView:self.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=logout&companyid=%@",kServerURL,companyId] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:self.view];
                [self.tableView.mj_header endRefreshing];
                if ([responseObject[@"status"] intValue] == 1) {
                    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
                    for (NSHTTPCookie * cookie in cookies){
                        //清除本地的Cookie (退出登录）
                        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
                    }
                    [UserDefaults setValue:@"0" forKey:@"isLogin"];
                    [UserDefaults removeObjectForKey:@"LoginTypeStr"];
                    [UserDefaults removeObjectForKey:@"userName"];
                    [UserDefaults removeObjectForKey:@"password"];
                    [UserDefaults removeObjectForKey:@"uid"];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"quitAction" object:nil userInfo:nil];
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                } else {
                    [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            }];
            
        } cancelBolck:^(void) {
            
        }];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}
// 清理缓存
- (void)clearFile
{
    NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
    NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
    //    NSLog ( @"cachpath = %@" , cachPath);
    for ( NSString * p in files) {
        NSError * error = nil ;
        NSString * path = [cachPath stringByAppendingPathComponent :p];
        if ([path isEqualToString:[cachPath stringByAppendingPathComponent:[UserDefaults valueForKey:@"adImageName"]]]) {
            NSLog(@"imagePath:%@",[cachPath stringByAppendingPathComponent:[UserDefaults valueForKey:@"adImageName"]]);
        } else {
            if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
                [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
            }
        }
        
    }
    [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
}
- (void)clearCachSuccess
{
    //    NSLog ( @" 清理成功 " );
    [TFHUD addRemindHUD:self.view message:@"清理成功"];
    //    NSIndexPath *index=[NSIndexPath indexPathForRow:0 inSection:1];//刷新
    //
    //    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight) style:(UITableViewStyleGrouped)];
        _tableView.backgroundColor = UIColorWhite;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
